package com.dco.dcowebhook.repository;

import com.dco.dcowebhook.model.WebhookEvent;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.dco.dcowebhook.dto.CommitStatusDTO;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

@Repository
public interface WebhookEventRepository extends JpaRepository<WebhookEvent, Long> {
    @Query("SELECT new com.dco.dcowebhook.dto.CommitStatusDTO(" +
            "we.repositoryName, we.repositoryOwner, we.pusher, " +
            "we.after, " +
            "CASE WHEN ic.sha IS NULL THEN true ELSE false END, " +
            "we.receivedAt) " +
            "FROM WebhookEvent we " +
            "LEFT JOIN InvalidCommitData ic ON we.after = ic.sha " +
            "WHERE (:repoName IS NULL OR we.repositoryName LIKE %:repoName%) " +
            "AND (:repoOwner IS NULL OR we.repositoryOwner LIKE %:repoOwner%) " +
            "AND (:pusher IS NULL OR we.pusher LIKE %:pusher%)")
    List<CommitStatusDTO> findCommitStatus(@Param("repoName") String repoName,
                                           @Param("repoOwner") String repoOwner,
                                           @Param("pusher") String pusher);
}
